/*
 Copyright (c) 2007 AppScrapper authors and contributors
 
 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:
 
 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */

#import "TDPreferencesWindowController.h"

#define PREFERENCES_TOOLBAR_IDENTIFIER  @"Preferences Toolbar Identifier"
#define GENERAL_TOOLBAR_IDENTIFIER      @"General Toolbar Identifier"
#define PROTECTION_TOOLBAR_IDENTIFIER   @"Protection Toolbar Identifier"


@implementation TDPreferencesWindowController

#pragma mark Singleton
TDPreferencesWindowController *sharedPreferencesWindowInstance = nil;

+ (TDPreferencesWindowController *) preferencesWindowController
{
    if (!sharedPreferencesWindowInstance)
        sharedPreferencesWindowInstance = [[self alloc] initWithWindowNibName:@"PreferencesWindow"];
    return sharedPreferencesWindowInstance;
}

#pragma mark Overrides
- (id) initWithWindowNibName:(NSString *)windowNibName
{
    if (!(self = [super initWithWindowNibName:windowNibName]))
        NSLog(@"initWithWindowNibName \"%@\" failed", windowNibName);
    else {
        defaults = [NSUserDefaults standardUserDefaults];
        
        // set play sound
        NSEnumerator *soundEnumerator,*voiceEnumerator,
            *soundDirectoriesEnumerator = [[NSArray arrayWithObjects: @"/System/Library/Sounds",
                [NSHomeDirectory() stringByAppendingPathComponent: @"Library/Sounds"], nil] objectEnumerator];
        NSString *soundPath, *sound, *voice;
		NSMutableArray * sounds = [NSMutableArray array], *voices = [NSMutableArray array];

        
        // get list of all sounds and sort alphabetically
        while ((soundPath = [soundDirectoriesEnumerator nextObject]))
            if (soundEnumerator = [[NSFileManager defaultManager] enumeratorAtPath: soundPath])
                while ((sound = [soundEnumerator nextObject])) {
                    sound = [sound stringByDeletingPathExtension];
                    if ([NSSound soundNamed: sound])
                        [sounds addObject: sound];
                }
        availableSounds = [[sounds sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)] retain];
		
		//set say voice
		voiceEnumerator = [[NSSpeechSynthesizer availableVoices] objectEnumerator];
		availableVoices = [NSMutableArray new];
		while(voice = [voiceEnumerator nextObject]){
			[voices addObject:[[NSSpeechSynthesizer attributesForVoice:voice] valueForKey:NSVoiceName]];
		}
		availableVoices = [voices copy];
    }
    return self;
}

- (void) windowDidLoad
{
    [self setupToolbar];
    [[self window] center];
}

#pragma mark Helpers
- (void) addSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info
{
    if (code == NSOKButton)
    {
        NSString *filePath;
        NSEnumerator *filenamesEnumerator = [[openPanel filenames] objectEnumerator];
        while ((filePath = [filenamesEnumerator nextObject])) {
            NSMutableDictionary *entry = [[[TDObject sharedAppScrapperInstance] protectionController] protectionEntryWithPath:filePath];
            if (!([[[TDObject sharedAppScrapperInstance] protectionController] isProtected:entry]))
                [[[TDObject sharedAppScrapperInstance] protectionController] addApp:entry];
        }
    }
}

#pragma mark IBActions
- (IBAction) addApp:(id)sender
{
    NSOpenPanel * panel = [NSOpenPanel openPanel];
    
    [panel setPrompt: @"Select"];
    [panel setAllowsMultipleSelection: YES];
    [panel setCanChooseFiles: YES];
    [panel setCanChooseDirectories: NO];
    [panel setCanCreateDirectories: NO];
    
    [panel beginSheetForDirectory: @"/Applications" file: nil types: [NSArray arrayWithObjects:@"app", nil]
                   modalForWindow: [self window] modalDelegate: self didEndSelector:
        @selector(addSheetClosed:returnCode:contextInfo:) contextInfo: nil];
}

- (IBAction)removeApp:(id)sender
{

}

- (IBAction) setSound:(id)sender
{
    // play sound when selecting
    NSString * soundName = [sender titleOfSelectedItem];
    NSSound * sound;
    if ((sound = [NSSound soundNamed: soundName]))
        [sound play];
}

#pragma mark Toolbar
- (void) setPrefView:(id) sender
{
    NSView *view = view_general;
    if (sender) {
        NSString *identifier = [sender itemIdentifier];
        if ([identifier isEqualToString: PROTECTION_TOOLBAR_IDENTIFIER])
            view = view_protection;
        else;
    }
    
    NSWindow *window = [self window];
    if ([window contentView] == view)
        return;
    
    NSRect windowRect = [window frame];
    int difference = [view frame].size.height - [[window contentView] frame].size.height;
    windowRect.origin.y -= difference;
    windowRect.size.height += difference;
    
    [view setHidden: YES];
    [window setContentView: view];
    [window setFrame: windowRect display: YES animate: YES];
    [view setHidden: NO];
    
    // set title label
    if (sender)
        [window setTitle: [sender label]];
    else
    {
        NSToolbarItem *item;
        NSEnumerator *enumerator = [[[[self window] toolbar] items] objectEnumerator];
        while ((item = [enumerator nextObject]))
            if ([[item itemIdentifier] isEqualToString: [[[self window] toolbar] selectedItemIdentifier]]) {
                [window setTitle: [item label]];
                break;
            }
    }
}

- (void) setupToolbar
{
    NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: PROTECTION_TOOLBAR_IDENTIFIER] autorelease];
    
    [toolbar setDelegate: self];
    [toolbar setAllowsUserCustomization: NO];
    [[self window] setToolbar: toolbar];
    [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
    [toolbar setSizeMode: NSToolbarSizeModeRegular];
    
    [toolbar setSelectedItemIdentifier: GENERAL_TOOLBAR_IDENTIFIER];
    [self setPrefView: nil];
}

- (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdent willBeInsertedIntoToolbar:(BOOL)flag 
{
    
    NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
    
    if ([itemIdent isEqual: GENERAL_TOOLBAR_IDENTIFIER]) {
        
        [toolbarItem setLabel: @"General"];
        [toolbarItem setToolTip: @"General"];
        [toolbarItem setImage: [NSImage imageNamed: @"Preferences.png"]];
        [toolbarItem setTarget: self];
        [toolbarItem setAction: @selector(setPrefView:)];
        [toolbarItem setAutovalidates: NO];
        
    } else if ([itemIdent isEqual: PROTECTION_TOOLBAR_IDENTIFIER]) {
        
        [toolbarItem setLabel: @"Protection"];
        [toolbarItem setToolTip: @"Protection"];
        [toolbarItem setImage: [NSImage imageNamed: @"agent.png"]];
        [toolbarItem setTarget: self];
        [toolbarItem setAction: @selector(setPrefView:)];
        [toolbarItem setAutovalidates: NO];
    } else
        toolbarItem = nil;
    
    return toolbarItem;
}

- (NSArray *) toolbarSelectableItemIdentifiers: (NSToolbar *)toolbar
{
    return [self toolbarDefaultItemIdentifiers: toolbar];
}

- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *)toolbar
{
    return [self toolbarAllowedItemIdentifiers: toolbar];
}

- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *)toolbar
{
    return [NSArray arrayWithObjects: GENERAL_TOOLBAR_IDENTIFIER, PROTECTION_TOOLBAR_IDENTIFIER, nil];
}

@end
